#include <zmq.hpp>
#include <iostream>
#include <chrono>
#include <string>
#include <deque>
#include <numeric>
#include <algorithm>

double calculate_moving_average(const std::deque<double>& delays) {
    double sum = std::accumulate(delays.begin(), delays.end(), 0.0);
    return sum / delays.size();
}

int main() {
    zmq::context_t context{1};
    zmq::socket_t socket{context, zmq::socket_type::pull};
    socket.connect("tcp://localhost:5555");

    std::deque<double> delays;
    int window_size = 10;

    while (true) {
        zmq::message_t zmq_message;
        socket.recv(zmq_message, zmq::recv_flags::none);

        // 获取当前时间作为接收时间戳
        auto end_time = std::chrono::high_resolution_clock::now();
        auto receive_timestamp = std::chrono::duration_cast<std::chrono::microseconds>(end_time.time_since_epoch()).count();

        // 将接收到的消息转换为字符串
        std::string message(static_cast<char*>(zmq_message.data()), zmq_message.size());

        // 将消息转换为时间戳
        auto send_timestamp = std::stoll(message);

        // 计算延时
        auto delay = static_cast<double>(receive_timestamp - send_timestamp);
        delays.push_back(delay);

        // 如果队列大小超过窗口大小，则移除最旧的值
        if (delays.size() > window_size) {
            delays.pop_front();
        }

        // 计算移动平均延时
        double avg_delay = calculate_moving_average(delays);

        // 计算最大值和最小值
        auto min_max = std::minmax_element(delays.begin(), delays.end());
        double min_delay = *min_max.first;
        double max_delay = *min_max.second;

        std::cout << "Raw delay: " << delay << " microseconds, "
                  << "Moving average delay: " << avg_delay << " microseconds, "
                  << "Min delay: " << min_delay << " microseconds, "
                  << "Max delay: " << max_delay << " microseconds" << std::endl;
    }

    return 0;
}
